import axios from 'axios'
import {Loading, Message} from 'element-ui'

const loading = {
    loadingInstance: null,
    // 打开加载
    open: function(){
        if(this.loadingInstance == null){
            this.loadingInstance = Loading.service({
                target: '.main',
                text: '拼命加载中...'
            })
        }
    },
    // 关闭加载
    close: function(){
        if(this.loadingInstance != null){
            this.loadingInstance.close()
        }
        this.loadingInstance = null
    }
}

const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000, //判断请求是否超时
})
// 拦截请求
request.interceptors.request.use(config => {
    loading.open()
    return config
}, error => {
    loading.close()
    return error
})
// 拦截响应
request.interceptors.response.use(response => {
    loading.close()
    // 后台响应不是2000说明问题
    const resp = response.data
    if(resp.code != 2000){
        Message({
            message: resp.message,
            type: 'warning',
            duration: 5000
        })
    }
    return response
}, error => {
    loading.close()
    Message({
        message: error.message,
        type: 'error',
        duration: 5000
    })
    return error
})
// 导出自定义创建axios对象
export default request

// axios.get('/db.json').then(response => {
//     const data = response.data
//     console.log(data)
// })